package com.fmy.mcsecurity.login.hander;

import com.fmy.mcsecurity.commons.tools.RequestTool;
import com.fmy.mcsecurity.config.filter.UsernamePassParamsHolder;
import com.fmy.mcsecurity.integration.TypeIntegration;
import com.fmy.mcsecurity.integration.TypeIntegrationHolder;
import com.fmy.mcsecurity.token.TokenManager;
import com.fmy.mcsecurity.token.model.SecurityToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @version 1.0
 * @Author MR.fmy
 * @Description 登录成功处理类
 * @Date 2019/5/14 0014 10:05
 **/
@Slf4j
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    private final LoginHandler loginHandler;
    private final TokenManager tokenManager;

    public AuthenticationSuccessHandlerImpl(LoginHandler loginHandler, TokenManager tokenManager) {
        this.loginHandler = loginHandler;
        this.tokenManager = tokenManager;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        //调用返回前辍
        loginHandler.resultPrefix();
        //数据返回
        try {
            String type = UsernamePassParamsHolder.getLoginType();
            String client = UsernamePassParamsHolder.getClient();
            SecurityToken token = tokenManager.generate(client, type, authentication);
            tokenManager.save(client, type, authentication, token);
            getComplete(type, authentication, token);
            RequestTool.responseWriter(response, HttpStatus.OK, loginHandler.resultSuccess(token));
        } catch (Exception e) {
            if (!(AuthenticationException.class.isAssignableFrom(e.getClass()))) {
                log.error(e.getMessage(), e);
            }
            RequestTool.responseWriter(response, HttpStatus.OK, loginHandler.resultFail(e));
        }

    }

    /**
     * 获取后置处理
     */
    private void getComplete(String type, Authentication authentication, SecurityToken token) {
        for (TypeIntegration integration : TypeIntegrationHolder.getAuthenticators()) {
            if (integration.support(type)) {
                integration.complete(authentication, token);
            }
        }
    }
}
